//
//  UIColor+Extension.swift
//  XMGTV
//
//  Created by Gary on 2018/3/8.
//  Copyright © 2018年 coderwhy. All rights reserved.
//

import UIKit

extension UIColor{
    //在分类中 给系统的类添加扩充函数 只能扩充便利构造函数
    // convenience  需要调用 self.init
    
    /// 自定义 RGBA 构造函数
    ///
    /// - Parameters:
    ///   - r: r
    ///   - g: g
    ///   - b: b
    convenience init(r : CGFloat, g : CGFloat, b : CGFloat, alpha : CGFloat = 1.0) {
        self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha)
    }
    
    /// 自定义便利构造函数 16进制  数值
    ///
    /// - Parameters:
    ///   - hud: 颜色数组
    ///   - alpha: 透明度
    convenience init?(hex : String , alpha : CGFloat = 1.0){
        
        guard hex.count >= 6 else {
            return nil
        }
        //1:转换成大写
        var tmpHex  = hex.uppercased()
        
        //去掉 0X ## #
        if tmpHex.hasPrefix("0x") || tmpHex.hasPrefix("##") {
            tmpHex = (tmpHex as NSString).substring(from: 2)
        }
        
        if tmpHex.hasPrefix("#") {
            tmpHex = (tmpHex as NSString).substring(from: 1)
        }
        
        //取出每个颜色的十六进制数字
        var range = NSMakeRange(0, 2)
        let rHex = (tmpHex as NSString).substring(with: range)
        range.location = 2
        let gHex = (tmpHex as NSString).substring(with: range)
        range.location = 4
        let bHex = (tmpHex as NSString).substring(with: range)
        
        //十六进制 转成 数字  扫描器
        var r : UInt32 = 0, g : UInt32 = 0,b: UInt32 = 0
        Scanner(string: rHex).scanHexInt32(&r)
        Scanner(string: gHex).scanHexInt32(&g)
        Scanner(string: bHex).scanHexInt32(&b)

        self.init(r: CGFloat(r), g: CGFloat(g), b: CGFloat(b), alpha: alpha)
        
    }
    
    
    /// 随机颜色的生成
    ///
    /// - Returns: UIColor
    class func randomColor() -> UIColor {
      return  UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
    }
    
}
